/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.us.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.us.entity.UsAttendanceAdp;
import com.thinkgem.jeesite.modules.us.service.UsAttendanceAdpService;
import com.thinkgem.jeesite.modules.warehouse.entity.BIWarehouseKpiData;

import org.apache.poi.ss.usermodel.Row;

/**
 * 美东美西正岗Controller
 * 
 * @author hui.li
 * @version 2016-09-24
 */
@Controller
@RequestMapping(value = "${adminPath}/us/usAttendanceAdp")
public class UsAttendanceAdpController extends BaseController {

	@Autowired
	private UsAttendanceAdpService usAttendanceAdpService;

	@ModelAttribute
	public UsAttendanceAdp get(@RequestParam(required = false) String id) {
		UsAttendanceAdp entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = usAttendanceAdpService.get(id);
		}
		if (entity == null) {
			entity = new UsAttendanceAdp();
		}
		return entity;
	}

	@RequiresPermissions("us:usAttendanceAdp:view")
	@RequestMapping(value = { "list", "" })
	public String list(UsAttendanceAdp usAttendanceAdp,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Page<UsAttendanceAdp> page = usAttendanceAdpService.findPage(
				new Page<UsAttendanceAdp>(request, response), usAttendanceAdp);
		model.addAttribute("page", page);
		return "modules/us/usAttendanceAdpList";
	}

	@RequiresPermissions("us:usAttendanceAdp:view")
	@RequestMapping(value = "form")
	public String form(UsAttendanceAdp usAttendanceAdp, Model model) {
		model.addAttribute("usAttendanceAdp", usAttendanceAdp);
		return "modules/us/usAttendanceAdpForm";
	}

	@RequiresPermissions("us:usAttendanceAdp:edit")
	@RequestMapping(value = "save")
	public String save(UsAttendanceAdp usAttendanceAdp, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, usAttendanceAdp)) {
			return form(usAttendanceAdp, model);
		}
		usAttendanceAdpService.save(usAttendanceAdp);
		addMessage(redirectAttributes, "保存美东美西正岗成功");
		return "redirect:" + Global.getAdminPath()
				+ "/us/usAttendanceAdp/?repage";
	}

	@RequiresPermissions("us:usAttendanceAdp:edit")
	@RequestMapping(value = "delete")
	public String delete(UsAttendanceAdp usAttendanceAdp,
			RedirectAttributes redirectAttributes) {
		usAttendanceAdpService.delete(usAttendanceAdp);
		addMessage(redirectAttributes, "删除美东美西正岗成功");
		return "redirect:" + Global.getAdminPath()
				+ "/us/usAttendanceAdp/?repage";
	}

	/**
	 * 美国正岗考勤数据导入
	 * 
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("us:usAttendanceAdp:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file,
			RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/us/usAttendanceAdp/list?repage";
		}
		try {
			ImportExcel ei = new ImportExcel(file, 0, 0);
			UsAttendanceAdp adp = null;
			String str  = "MM/dd/yyyy HH:mm:ss";
			//String str2 = "MM/dd/yyyy HH:mm:ss AM";
			SimpleDateFormat sdf = null;
			for (int i = ei.getDataRowNum(); i <= ei.getLastDataRowNum(); i++) {
				try {
					Row row = ei.getRow(i);
					adp = new UsAttendanceAdp();
					for (int j = 0; j < ei.getLastCellNum(); j++) {
						Object val = ei.getCellValue(row, j);
						switch (j) {
						case 0:
							adp.setCompanyCode(String.valueOf(val));
							break;
						case 1:
							adp.setEmployeeId(String.valueOf(val));
							break;
						case 2:
							adp.setLastName(String.valueOf(val));
							break;
						case 3:
							adp.setPayrollId(String.valueOf(val));
							break;
						case 4:
							adp.setSupervisor(String.valueOf(val));
							break;
						case 5:
							adp.setPayCycles(String.valueOf(val));
							break;
						case 6:
							adp.setOutType(String.valueOf(val));
							break;
						case 7:
							adp.setWorkedDepartment(String.valueOf(val));
							break;
						case 8:
							adp.setState(String.valueOf(val));
							break;
						case 9:
							String value = String.valueOf(val);
							sdf = new SimpleDateFormat(str,Locale.US);	
							Date date = sdf.parse(value);
							adp.setInTime(date);
							break;
						case 10:
							String dateOutValue = String.valueOf(val);
							sdf = new SimpleDateFormat(str,Locale.US);
							Date dateOut = sdf.parse(dateOutValue);
							adp.setOutTime(dateOut);
							break;
						case 11:
							adp.setOutPunchType(String.valueOf(val));
							break;
						case 12:
							adp.setHours(String.valueOf(val));
							break;
						case 13:
							adp.setEarningsCode(String.valueOf(val));
							break;
						default:
							adp.setNotes(String.valueOf(val));
							break;
						}
					}
					// 当天考勤工时>0的记录计入出勤人数；（工时工时为0，或空格，或文字的都不应计入人数）
					Double hours = Double.valueOf(adp.getHours());
					if ("PTO".equals(adp.getEarningsCode()) || hours <= 0) {
						continue;
					}
					usAttendanceAdpService.save(adp);
				} catch (Exception e) {
					// TODO: handle exception
					logger.error("美国正岗定时解析文件错误" + e.getMessage(), e);
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			addMessage(redirectAttributes,
					"美国正岗考勤数据导入失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/us/usAttendanceAdp/list?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * 
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据导入模板.xlsx";
			List<User> list = Lists.newArrayList();
			list.add(UserUtils.getUser());
			new ExportExcel("用户数据", User.class, 2).setDataList(list)
					.write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 仓库BI报表
	 * 
	 * @param biWarehouseKpiData
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("us:usAttendanceAdp:view")
	@RequestMapping(value = { "biwrehouseKpiList", "" })
	public String findAllListBIWarehouseKpi(
			@RequestParam(required = false) String warehouse,
			@RequestParam(required = false) String companyCode,
			BIWarehouseKpiData biWarehouseKpiData, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		biWarehouseKpiData.setWarehouse(warehouse);
		biWarehouseKpiData.setCompanyCode(companyCode);
		Page<BIWarehouseKpiData> page = usAttendanceAdpService
				.findAllListBIWarehouseKpi(new Page<BIWarehouseKpiData>(
						request, response), biWarehouseKpiData);
		model.addAttribute("page", page);
		model.addAttribute("warehouse", warehouse);
		model.addAttribute("companyCode", companyCode);
		model.addAttribute("biWarehouseKpiData", biWarehouseKpiData);
		return "modules/us/biwrehouseKpiList";
	}

	/**
	 * 导出考勤数据
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("us:usAttendanceAdp:view")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(HttpServletRequest request,
			HttpServletResponse response,
			RedirectAttributes redirectAttributes,
			BIWarehouseKpiData biWarehouseKpiData) {
		try {
			String fileName = "仓库KPI监控BI报表"
					+ DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<BIWarehouseKpiData> page = usAttendanceAdpService
					.findAllListBIWarehouseKpi(new Page<BIWarehouseKpiData>(
							request, response, -1), biWarehouseKpiData);
			new ExportExcel("仓库KPI监控BI报表", BIWarehouseKpiData.class)
					.setDataList(page.getList()).write(response, fileName)
					.dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出考勤失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath()
				+ "/us/usAttendanceAdp/?repage";
	}

	/**
	 * 导出考勤数据
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("us:usAttendanceAdp:view")
	@RequestMapping(value = "export2", method = RequestMethod.POST)
	public String exportFile(HttpServletRequest request,
			HttpServletResponse response,
			RedirectAttributes redirectAttributes,
			UsAttendanceAdp usAttendanceAdp) {
		try {
			String fileName = "美国正岗考勤数据" + DateUtils.getDate("yyyyMMddHHmmss")
					+ ".xlsx";
			Page<UsAttendanceAdp> page = usAttendanceAdpService.findPage(
					new Page<UsAttendanceAdp>(request, response, -1),
					usAttendanceAdp);
			new ExportExcel("美国正岗考勤数据", UsAttendanceAdp.class)
					.setDataList(page.getList()).write(response, fileName)
					.dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "美国正岗导出考勤失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath()
				+ "/us/usAttendanceAdp/?repage";
	}

}
